/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import DataAccess.DataAccessFacade;

import DomainModel.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author Mershack/Patrick
 */
@WebServlet(name = "AdminSectionController", urlPatterns = {"/AdminSectionContoller"})
public class AdminSectionController extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("currentUser");

        if (user == null || user.getRole() != Role.ADMIN) {
            request.getRequestDispatcher("/login").forward(request, response);
        }
    }

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        String action = request.getParameter("action");

        if (action != null && action.equals("loadSections")) {
            doLoadSections(request, response);
        }
       request.getRequestDispatcher("/WEB-INF/grs/adminSectionsView.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);

        String actionAddSection = request.getParameter("addSection");
        String actionEditSection = request.getParameter("editSection");
        String submitDeleteSection = request.getParameter("submitDeleteSection");
        String actionEnrollSection = request.getParameter("enrollSection");
        String submitSection = request.getParameter("submitSection");
        String cancelSubmitSection = request.getParameter("cancelSubmitSection");
        try {
            List<User> professors = DataAccessFacade.getInstance().getAllProfessors();
            request.setAttribute("professors", professors);

            List<Course> courseList = DataAccessFacade.getInstance().getAllCourses();
            request.setAttribute("courseList", courseList);
//            List<Weekday> dayList = DataAccessFacade.getInstance().getAllWeekdays();
          //  request.setAttribute("dayList", dayList);

        } catch (Exception ex) {
            Logger.getLogger(AdminSectionController.class.getName()).log(Level.SEVERE, null, ex);
        }

        // ADD section
        if (actionAddSection != null) {
            request.getRequestDispatcher("/WEB-INF/grs/adminSectionsAdd.jsp").forward(request, response);
        }
        if (actionEditSection != null) { // EDIT section
            doEditSection(request, response);
        }
        if (actionEnrollSection != null) { //enroll section
            String strSectionId = request.getParameter("inputSectionId");
            response.sendRedirect("adminEnroll?sid=" + strSectionId);
        } 
        
        if(submitDeleteSection != null) {
           doDeleteSection(request,response);
           request.getRequestDispatcher("/WEB-INF/grs/adminSectionsView.jsp").forward(request, response);
        } else if (cancelSubmitSection != null) { // CANCEL submitting a section
            request.getRequestDispatcher("/WEB-INF/grs/adminSectionsView.jsp").forward(request, response);
        } else if (submitSection != null) { // SUBMIT add/edit section
            if (doAddSection(request, response)) {
                request.getRequestDispatcher("/WEB-INF/grs/adminSectionsView.jsp").forward(request, response);
            } else {
                request.getRequestDispatcher("/WEB-INF/grs/adminSectionsAdd.jsp").forward(request, response);
            }
        }
    }

    protected void doLoadSections(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            DataAccessFacade dataAccessFacade = DataAccessFacade.getInstance();
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                List<Section> allSections = dataAccessFacade.getAllSections();
                JSONArray allSectionsJson = new JSONArray();

                for (Section section : allSections) {
                    JSONObject sectionJson = new JSONObject();

                    sectionJson.put("SectionId", section.getSectionID());
                    sectionJson.put("SectionName", section.getSectionName());
                    sectionJson.put("ProfId", section.getProfessor().getUserId());
                    sectionJson.put("ProfessorName", section.getProfessor().getFirstName() + " " + section.getProfessor().getLastName());
                    sectionJson.put("CourseId", section.getCourse().getCourseId());
                    sectionJson.put("CourseName", section.getCourse().getCourseName());
                    sectionJson.put("SemesterTypeId", section.getSemesterType().getSemesterTypeId());
                    sectionJson.put("SemesterTypeName", section.getSemesterType().getSemesterName());
                    sectionJson.put("SemesterYear", section.getSemesterYear());
                    allSectionsJson.put(sectionJson);
                }
                String allSectionsStr = allSectionsJson.toString();
                out.print(allSectionsStr);
                
            } catch (Exception e) {
            } finally {
                out.close();
            }
        } catch (Exception e) {
        }
    }

    private void doEditSection(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("inputSectionId", request.getParameter("inputSectionId")); 
        request.setAttribute("inputSectionName", request.getParameter("inputSectionName"));
        request.setAttribute("inputProfId", request.getParameter("inputProfId")); //needs validity checks
        request.setAttribute("inputCourseId", request.getParameter("inputCourseId")); // needs validity checks
        request.setAttribute("inputSemesterTypeId", request.getParameter("inputSemesterTypeId"));
        request.setAttribute("inputSemesterYear", request.getParameter("inputSemesterYear"));
        request.getRequestDispatcher("/WEB-INF/grs/adminSectionsAdd.jsp").forward(request, response);
    }

    private void doDeleteSection(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String strInputSectionId = request.getParameter("inputSectionId");
        int sectionId = Integer.parseInt(strInputSectionId);
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);
        try { 
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("currentUser");
            boolean result = DataAccessFacade.getInstance().deleteSection(user.getUserId(), sectionId);

            if (result) {
                messages.put("success", "Section deleted successfully");
            }
            else {
                messages.put("error", "Could not delete this section.");
            }
        }
        catch (Exception e) {
            messages.put("error", "An error occurred while deleting this section");
        }    
       // finally {
           // request.getRequestDispatcher("/WEB-INF/grs/adminSectionsView.jsp").forward(request, response);
       // }
    }
    
    
    
    private boolean doAddSection(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String, String> messages = new HashMap<>();
        request.setAttribute("messages", messages);
        try {
            String strSectionId = request.getParameter("inputSectionId");
            String strSectionName = request.getParameter("inputSectionName");
            String strProfId = request.getParameter("inputProfId");
            String strCourseId = request.getParameter("inputCourseId");
            String strSemesterType = request.getParameter("inputSemesterType");
            String strSemesterYear = request.getParameter("inputSemesterYear");
            int sectionId = (strSectionId == null || strSectionId.isEmpty()) ? 0 : Integer.valueOf(strSectionId);
            int semesterYear = Integer.valueOf(strSemesterYear);
            request.setAttribute("inputSectionId", strSectionId);
            request.setAttribute("inputSectionName", strSectionName);
            request.setAttribute("inputProfId", strProfId);
            request.setAttribute("inputCourseId", strCourseId);
            request.setAttribute("inputSemesterType", strSemesterType);
            request.setAttribute("inputSemesterTypeId", SemesterType.valueOf(strSemesterType));
            request.setAttribute("inputSemesterYear", strSemesterYear);

            String missingFields = "";
            if (strSectionName == null || strSectionName.isEmpty()) {
                missingFields = "Section Name";
            }
            if (strProfId == null || strProfId.isEmpty()) {
                missingFields += missingFields.isEmpty() ? "Professor ID" : ", Professor ID";
            }
            if (strCourseId == null || strCourseId.isEmpty()) {
                missingFields += missingFields.isEmpty() ? "Course ID" : ", Course ID";
            }

            if (strSemesterType == null || strSemesterType.isEmpty()) {
                missingFields += missingFields.isEmpty() ? "Semester" : ", Semester";
            }
            
            if (strSemesterYear == null || strSemesterYear.isEmpty()) {
                missingFields += missingFields.isEmpty() ? "Year" : ", Year";
            }
            if (!missingFields.isEmpty()) {
                messages.put("error", "Please provide the following fields: " + missingFields);
                return false;
            }
            User prof = DataAccessFacade.getInstance().getUserById(Integer.valueOf(strProfId));
            Course course = DataAccessFacade.getInstance().getCourseById(Integer.valueOf(strCourseId));
            SemesterType semType = SemesterType.valueOf(strSemesterType);
            Section section = new Section(sectionId, strSectionName, prof, course, semType, semesterYear);
            DataAccessFacade.getInstance().setSection(section);

            String msg = (sectionId == 0) ? "Section added successfully." : "Section edited successfully.";
            messages.put("success", msg);
        } catch (Exception e) {
            messages.put("error", "An error occurred adding the section.");
            return false;
        }
        return true;
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
